package com.fivetiger.service.impl;

import com.alibaba.excel.EasyExcel;
import com.fivetiger.dao.MasterDao;
import com.fivetiger.entity.Master;
import com.fivetiger.listener.MasterReadListener;
import com.fivetiger.service.inte.MasterService;
import com.fivetiger.util.RUtil;
import com.fivetiger.vo.PageBean;
import com.fivetiger.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service //IOC
public class MasterServiceImpl implements MasterService {
    @Autowired
    private MasterDao masterDao;
    @Override
    public R save(Master master) {
        if(masterDao.insert(master)>0){

            return RUtil.ok();
        }else {
            return RUtil.fail();
        }
    }

    @Override
    public PageBean queryPage() {
        List<Master> list=masterDao.selectAll();
        return new PageBean(0,"",list.size(),list);
    }

    @Override
    public R saveBatch(MultipartFile file) {
        //1.校验
        if(!file.isEmpty()){
            //2.获取文件内容
            try {
                InputStream is=file.getInputStream();
                //3.实例化自定义监听器
                MasterReadListener masterReadListener=new MasterReadListener();
                //4.解析Excel
                List<Master>list= EasyExcel.read(is,Master.class,masterReadListener).doReadAllSync();
                //5.获取解析的结果,执行批处理
                if(masterDao.insertBatch(list)>0){
                    return RUtil.ok(0);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return RUtil.fail();
    }

    @Override
    public R saveBatchV2(MultipartFile file) {
        return null;
    }

    @Override
    public R change(Master master) {
        if (masterDao.update(master)>0){
            return RUtil.ok();
        }else {
            return RUtil.fail();
        }
    }
}
